package com.atom.app.mvvm.ui.fragments

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import com.atom.app.mvvm.AppModel
import com.atom.app.mvvm.BR
import com.atom.app.mvvm.R
import com.atom.app.mvvm.VMFactory
import com.atom.app.mvvm.abase.BaseKingFragment
import com.atom.app.mvvm.abase.BaseKingViewModel
import com.atom.app.mvvm.Contacts
import com.atom.app.mvvm.databinding.FragmentTaskBinding
import com.atom.app.mvvm.net.BaseResponse
import com.atom.app.mvvm.net.bean.TaskInfo
import com.atom.app.mvvm.ui.activities.TaskDetailActivity
import com.atom.app.mvvm.utils.AbstractAdapter
import com.atom.app.mvvm.utils.AbstractViewHolder
import com.atom.module.mvvm.livedata.SingleLiveData
import com.atom.module.mvvm.util.Auto
import com.atom.module.reporter.CrashReporter
import com.scwang.smart.refresh.footer.ClassicsFooter
import com.scwang.smart.refresh.header.ClassicsHeader
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import io.reactivex.rxjava3.internal.observers.BlockingBaseObserver
import io.reactivex.rxjava3.schedulers.Schedulers

class TaskFragment : BaseKingFragment<FragmentTaskBinding, TaskViewModel>() {

    var userName: String = "赵芳宇"

    override fun initArgs(savedInstanceState: Bundle?) {
        super.initArgs(savedInstanceState)
        Auto.registerTask(this::class) { app ->
            viewModel.getTask()
            true
        }
        savedInstanceState ?: return
        userName = savedInstanceState.getString(Contacts.tag_username, "赵芳宇")
    }

    override fun onNewIntent(bundle: Bundle?): Boolean {
        bundle ?: return false
        userName = bundle.getString(Contacts.tag_username, "赵芳宇")
        viewModel.getTask(userName)
        return true
    }

    override fun initContentView(
        inflater: LayoutInflater?,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): Int {
        return R.layout.fragment_task
    }

    override fun initViewModel(): TaskViewModel {
        return ViewModelProvider(this, VMFactory).get(TaskViewModel::class.java)
    }

    override fun initVariableId(): Int {
        return BR.taskViewModel
    }

    override fun initViewBinding(binding: FragmentTaskBinding, viewModel: TaskViewModel) {
        super.initViewBinding(binding, viewModel)
        viewModel.finishRefreshEvent.observe(this) {
            binding.taskUpdate.finishRefresh()
        }
        // 布局刷新
        binding.taskUpdate.setRefreshHeader(ClassicsHeader(requireContext()))
        binding.taskUpdate.setRefreshFooter(ClassicsFooter(requireContext()))
        binding.taskUpdate.setEnableRefresh(true)
        //binding.taskUpdate.setEnableLoadMore(true)
        binding.taskUpdate.setOnRefreshListener {
            viewModel.getTask()
        }
        binding.taskUpdate.setOnLoadMoreListener { refreshlayout ->
            toastShow("敬请期待")
        }
        // binding.taskUpdate.autoRefresh()
        binding.taskList.layoutManager = LinearLayoutManager(requireContext())
        binding.taskList.adapter = viewModel.adapter
    }

    override fun initData(view: View) {
        super.initData(view)
        if (!Auto.startTask(this)) {
            viewModel.getTask(userName)
        }
    }
}


class TaskViewModel : BaseKingViewModel<AppModel>(AppModel) {

    val adapter = object : AbstractAdapter<TaskInfo.Data>() {
        override fun getItemViewType(position: Int, data: TaskInfo.Data): Int {
            return R.layout.item_task_info
        }

        override fun onCreateViewHolder(
            contentView: View,
            viewType: Int
        ): AbstractViewHolder<TaskInfo.Data> {
            return ViewHolder(contentView)
        }
    }

    var finishRefreshEvent: SingleLiveData<Unit> = SingleLiveData()

    inner class ViewHolder(v: View) : AbstractViewHolder<TaskInfo.Data>(v) {
        override fun onBind(data: TaskInfo.Data) {
            view(R.id.name) { t: TextView ->
                t.text = data.schemeName
            }
            view(R.id.outlets) { t: TextView ->
                t.text = data.fields?.companyName
            }
            view(R.id.superior) { t: TextView ->
                t.text = data.parentName
            }
            view(R.id.achievement) { t: TextView ->
                t.text = data.total?.toString()
            }
            view(R.id.status) { t: TextView ->
                t.text = data.fields?.status
                when (data.fields?.status) {
                    "已申述", "审核通过" -> {
                        t.setBackgroundColor(t.resources.getColor(R.color.cc4CAF50))
                    }
                    "未提交" -> {
                        t.setBackgroundColor(t.resources.getColor(R.color.cc0274B2))
                    }
                }
            }
            view(R.id.openDetails) { t: View ->
                t.setOnClickListener {
                    startActivity(TaskDetailActivity::class.java, Bundle().apply {
                        this.putInt(Contacts.tag_task_id, data.pk ?: -1)
                    })
                }
            }
        }
    }

    fun getTask(trueName: String = "赵芳宇") {
        addSubscribe(
            model.netApi.getAllTask(myName = "admin", trueName = trueName)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeWith(object : BlockingBaseObserver<BaseResponse<List<TaskInfo.Data>>>() {
                    override fun onNext(t: BaseResponse<List<TaskInfo.Data>>) {
                        t.data?.also {
                            adapter.replaceAll(it)
                        }
                        finishRefreshEvent.setValue(Unit)
                    }

                    override fun onError(e: Throwable) {
                        CrashReporter.reportException(e.localizedMessage)
                        finishRefreshEvent.setValue(Unit)
                    }
                })
        )
    }
}
